<?php

require("phpmailer/class.phpmailer.php");

class Email extends Module
{
	var $mail;
	var $header = '<html><head><title></title></head>
			<body>
			  <table cellpadding = "0" cellspacing = "0" border = "0">
				<tr>
				  <td><img src = "http://dsentiment.com/waterfantasy/html/email/header.png"></td>
				</tr>
				<tr>
					<td style = "padding:20px;">
			';
	var	$footer = '</td>
				</tr>
				<tr>
				  <td><img src = "http://dsentiment.com/waterfantasy/html/email/footer.png"></td>
				</tr>
			  </table>
			</body>
			</html>
			';

	function __construct ($db){
		$this->set_db($db);

		$this->mail = new PHPMailer();
		/*
		$this->mail->IsSMTP();
		$this->mail->SMTPDebug = 0;
		$this->mail->SMTPAuth = true;
		$this->mail->SMTPSecure = "ssl";
		$this->mail->Mailer = "smtp";
		$this->mail->Host = 'smtp.gmail.com';
		$this->mail->Port = 465;
		*/

		//$this->mail->CharSet="utf-8";
		$this->mail->IsHTML(true);

		//$this->set_account();
	}

	function set_account(){

		$sql = "SELECT * FROM email_account";
		$rss = $this->db->query($sql);

		if($line = $this->db->fetchNextObject($rss)){
			$this->mail->Username = $line->email; // ต้องมีเมล์ของ gmail ที่สมัครไว้ด้วยนะครับ
			$this->mail->Password = $line->password; // ใส่ password ที่เราจะใช้เข้าไปเช็คเมล์ที่ gmail ล่ะครับ
		}
	}

	function set_form($name){

		$sql = "SELECT * FROM email WHERE name = '$name'";
		$rss = $this->db->query($sql);

		if($line = $this->db->fetchNextObject($rss)){
			$this->mail->Subject = "=?UTF-8?B?".base64_encode($line->subject)."?=";
			$this->mail->Body = $this->header . $line->message . $this->footer;
			$this->mail->AltBody =  $this->header . $line->message . $this->footer;
			$this->mail->FromName = $line->from;
			$this->mail->AddReplyTo($line->email);
//			$this->mail->From = $line->email;
			$this->mail->SetFrom($line->email, $line->from);
		}
	}
	
	function fill($word, $replace){
		$this->mail->Body = str_replace("#".$word."#", $replace, $this->mail->Body);
	}

	function send_to($email){

		if(strstr($email,";")){
			$email = explode(";", $email);
		}else{
			$email = explode(",", $email);
		}

		for($i = 0; $i < count($email); $i++){
			$this->mail->AddAddress(trim($email[$i]));
		}
	}

	function add_cc($email){
		$this->mail->AddCC($email);
	}

	function send(){
		$this->mail->Send();
	}
}

?>